<template>
  <PageWrapper>
    <n-card >
      <n-tabs type="line" animated>
        <n-tab-pane name="oasis" tab="充电宝">
          <!-- Wonderwall -->
          <Bao/>
        </n-tab-pane>
        <n-tab-pane name="the beatles" tab="充电盒子">
          <!-- Hey Jude -->
          <Boxz/>
        </n-tab-pane>
        <n-tab-pane name="jay chou" tab="充电线">
          <!-- 七里香 -->
          <Linee/>
        </n-tab-pane>
      </n-tabs>
    </n-card>
    

  </PageWrapper>
</template>

<script lang="ts" setup>
  import { h, reactive, ref, onMounted } from 'vue';
  import { useMessage, FormRules } from 'naive-ui';
  import { BasicColumn, BasicTable, TableAction } from '@/components/Table';
  import { chargerlist,batterylist,openport,offport,openAllPort,openResult1,getallStationList,batchCharger,bussinessCharger,getStationList1 } from '@/api/device/charger';
  import { getallagentList,getallagentList1 } from '@/api/system/user';
  import { FileAddOutlined, SearchOutlined } from '@vicons/antd';
  import CreateDrawer from './CreateDrawer.vue';
  import { columns } from './columns';
  import Bao from './componse/devicebao/bao.vue';
  import Boxz from './componse/deviceboxz/boxz.vue';
  import Linee from './componse/line/line.vue';
  import type { UploadFileInfo } from 'naive-ui'
  import { useGlobSetting } from '@/hooks/setting';
  import { useRouter } from 'vue-router';
  import type { formParamsType } from './types';
  const router = useRouter();
  const globSetting = useGlobSetting();
  const { uploadUrl } = globSetting;
  const uploadUrl1 = uploadUrl;

  const showModal = ref(false);
  const message = useMessage();
  const basicTableRef = ref();
  const rowKeys = ref([]);
  const rowKeysName = ref([]);
  const rowkeysChargerName = ref([]);
  const tableData = ref();
  const createDrawerRef = ref();
  const drawerTitle = ref('添加充电宝');
  const roleData = ref([]);
  const modalShow = ref(false);
  const showBatchModal = ref(false);
  const batteryList = ref([]);
  const showStationModal = ref(false);
  const showModalagent = ref(false);
  const agentAll = ref([]);
  const stationAll = ref([]);
  const subLoading = ref(false);
  const formRef: any = ref(null);
  const businessesModal = ref(false);

  const defaultValueRef = () => ({
    ids: null,
    charger_agents_name: '',
    charger_agents_id: 0,
    charger_station_name: '',
    charger_station_id: 0,
    charger_bussiness_id: 0,
    charger_bussiness_name: ''
  });

  const formParams1 = ref<formParamsType>(defaultValueRef());

  const rules1: FormRules = {
    username: {
      required: true,
      message: '登录账号不能为空',
      trigger: 'blur',
    },
    nickname: {
      required: true,
      message: '名称不能为空',
      trigger: 'blur',
    },
    roleIds: {
      required: true,
      message: '角色不能为空',
      trigger: 'change',
      type: 'number',
    },
    password: {
      required: true,
      message: '密码不能为空',
      trigger: 'blur',
    },
    // dept_id: {
    //   required: true,
    //   message: '部门不能为空',
    //   trigger: 'change',
    //   type: 'number',
    // },
  };

  const params = reactive({
    name: '',
    charger_number: '',
    charger_agents_name: '',
    charger_bussiness_name: '',
  });

  const handleFinish = ({
    file,
    event
  }: {
    file: UploadFileInfo
    event?: ProgressEvent
  }) => {
    console.log("打印上传后信息")
    console.log(event)
    // console.log();
    // message.success((event?.target as XMLHttpRequest).response.message)

    var returnJson = (event?.target as XMLHttpRequest).response;
    let All = JSON.parse(returnJson);

    message.success(All.message);



    // const ext = file.name.split('.')[1];//文件后缀名
    // console.log("打印依稀啊这个");
    



    // console.log(ext);

    // file.name = `更名.${ext}`
    // file.url = '__HTTPS__://www.mocky.io/v2/5e4bafc63100007100d8b70f'
    // return file

  }



  function downmo(){
    console.log("打印一下下载的路径");
    // console.log(g.development.BASEURL);
    // console.log(g.development.BASEURL + '/moban.xlsx')
    // return;
    window.open(g.development.BASEURL + '/moban.xlsx','_self');
  }

  const aShow = ref(false);
  const businessesAll = ref([]);
  const chargerParams = ref({
    name:'',
    page:1,
    pageSize:10,
    totalPage:1,
    charger_agents_id:''
  });

  const stationParams = ref({
    name:'',
    page:1,
    pageSize:10,
    totalPage:1,
    charger_agents_id:''
  });

  const stationAllParams = ref({
    name: '',
    page: 1,
    pageSize: 10,
    totalPage: 1,
    charger_agents_id: 0,
    charger_bussiness_id: 0
  });

  function handleBusinesses(){
    businessesModal.value = true;
  }

      //代理商搜索
  async function chaSearchBut(){
    var agentAll1 = await getallagentList1(chargerParams.value);
    console.log("打印一下所有的代理商ok")
    console.log(agentAll1);
    chargerParams.value.totalPage = agentAll1.totalPage;
    agentAll.value = agentAll1.list;
  }

  //代理商分页
  async function chargerChangePage(e){
    // console.log("改变时候触发");
    // console.log(e);
    //改变一下页数
    chargerParams.value.page = e;
    //重新请求一下接口
    var agentAll1 = await getallagentList1(chargerParams.value);
    console.log("打印一下所有的代理商ok")
    console.log(agentAll1);   
    chargerParams.value.totalPage = agentAll1.totalPage;
    agentAll.value = agentAll1.list;
  }
  async function chargerChangePagesize(e){
    // console.log("改变时候触发");
    // console.log(e);
    //改变条数
    chargerParams.value.pageSize = e;


    var agentAll1 = await getallagentList1(chargerParams.value);
    console.log("打印一下所有的代理商ok")
    console.log(agentAll1);   
    chargerParams.value.totalPage = agentAll1.totalPage;
    agentAll.value = agentAll1.list;
  }

  //门店分页
  async function stationAllChangePage(e){
    // console.log("改变时候触发");
    // console.log(e);
    //改变一下页数
    stationAllParams.value.page = e;
    stationAllList();
    //重新请求一下接口
    // var result = await bussinessCharger(stationParams.value);
    // stationParams.value.totalPage = result.totalPage;
    // businessesAll.value = result.list;
  }
  async function stationAllChangePagesize(e){
    // console.log("改变时候触发");
    // console.log(e);
    //改变条数
    stationAllParams.value.pageSize = e;
    stationAllList();
    // var result = await bussinessCharger(stationParams.value);

    // stationParams.value.totalPage = result.totalPage;
    // businessesAll.value = result.list;
  }

  //商家分页
  async function stationChangePage(e){
    // console.log("改变时候触发");
    // console.log(e);
    //改变一下页数
    stationParams.value.page = e;
    //重新请求一下接口
    var result = await bussinessCharger(stationParams.value);
    stationParams.value.totalPage = result.totalPage;
    businessesAll.value = result.list;
  }
  
  async function stationChangePagesize(e){
    // console.log("改变时候触发");
    // console.log(e);
    //改变条数
    stationParams.value.pageSize = e;

    var result = await bussinessCharger(stationParams.value);

    stationParams.value.totalPage = result.totalPage;
    businessesAll.value = result.list;
  }


  function selectBusinesses(item){
    //商户id
    formParams1.value.charger_bussiness_id = item.id;
    //商户名称
    formParams1.value.charger_bussiness_name = item.username;
    
    businessesModal.value = false;

    //门店搜索
    stationAllList();

  }

  //商家搜索
  async function staSearchBut(){
    var result = await bussinessCharger(stationParams.value);
    stationParams.value.totalPage = result.totalPage;
    businessesAll.value = result.list;
  }



  const actionColumn: BasicColumn = reactive({
    width: 170,
    title: '操作',
    key: 'action',
    fixed: 'right',
    align: 'center',
    render(record) {
      return h(TableAction as any, {
        actions: [
          {
            label: '编辑',
            onClick: handleEdit.bind(null, record),
          },
          {
            label: '设备详情',
            onClick: findPortHandle.bind(null, record),
          },
        ],
      });
    },
  });

  const loadDataTable = async (res) => {
    const result = await chargerlist({ ...params, ...res });
    tableData.value = result.list;
    return result;
  };

  function selectStation(item){
    formParams1.value.charger_station_id = item.id;
    formParams1.value.charger_station_name = item.name;
    showStationModal.value = false;
  }


  async function selectAgent(item){
    //代理商id
    formParams1.value.charger_agents_id = item.id;
    //代理商名称
    formParams1.value.charger_agents_name = item.username;

    formParams1.value.charger_bussiness_id = 0;
    formParams1.value.charger_bussiness_name = '';


    stationParams.value.charger_agents_id = item.id;

    //查询商户
    var result = await bussinessCharger(stationParams.value);

    stationParams.value.totalPage = result.totalPage;
    businessesAll.value = result.list;

    //门店搜索
    stationAllList();

    showModalagent.value = false;
  }

  async function stationAllList(){
    // console.log("打印调用一下")

    // console.log(formParams1.value.charger_bussiness_id);
    if( formParams1.value.charger_bussiness_id == 0 && formParams1.value.charger_agents_id == 0 ){
      message.error("请选择归属代理商或归属商户");
    }else{//查询一下归属代理商的值

      stationAllParams.value.charger_agents_id = formParams1.value.charger_agents_id;

      stationAllParams.value.charger_bussiness_id = formParams1.value.charger_bussiness_id;
      
      var all123 = await getStationList1(stationAllParams.value);

      // console.log("打印一下所有的");
      // console.log(all123);

      stationAllParams.value.totalPage = all123.totalPage;

      stationAll.value = all123.list;
    }


    // var stationAll1 = await getallStationList({});

    // stationAll.value = stationAll1;

  }

  function openResult(){
    var charger_number = batteryList.value[0].charger_number;
    aShow.value = true;

    openResult1({'charger_number': charger_number}).then((res) => {
      // console.log(res)
      
      setTimeout(() => {
          aShow.value = false;  
          message.success('发送成功！');
          handleReset1(charger_number);
          reloadTable();  
          
      }, 500);

    }).catch((error) => {
      aShow.value = false;
    });

  }

  //一键弹出
  function openAllTan(){
    var charger_number = batteryList.value[0].charger_number;
    aShow.value = true;
    console.log("打印一下充电宝的编号")
    console.log(charger_number)

    openAllPort({'charger_number': charger_number}).then((res) => {
      // console.log(res)
      
      setTimeout(() => {
        aShow.value = false;  
        message.success('发送成功！');
          handleReset1(charger_number);
          reloadTable();  
          
      }, 5000);

    }).catch((error) => {
      aShow.value = false;
    });

  }

  //强制弹出充电口
  function openPortCharging(item){
    aShow.value = true;
    // if(item.power == 1){
    //   message.error('该充电口已锁定！');
    //   return;
    // }

    var portCharging = {
      "sn":item.charger_number,
      'port':item.port,
    };

    openport(portCharging).then((res) => {
      // console.log(res);
      
        setTimeout(() => {
          aShow.value = false;
          message.success('发送成功！');
          handleReset1(item.charger_number);  
          reloadTable();  
          
        }, 2000);
        
      // if(res == 1){
        // emit('change');
        
        
      // }
      
      
      // handleReset();
      // closeDrawer();
      
    }).catch((error) => {
      aShow.value = false;
    });


  }

  //禁用开始
  function endPortCharging(item){

    var power = 0;
    if(item.power == 0){
      power = 1;
    }else{
      power = 0;
    }

    var portCharging = {
      "sn": item.charger_number,
      'port': item.port,
      'power': power
    };


    offport(portCharging).then((res) => {
      // console.log(res);
      // message.success('发送成功！');
      // emit('change');
      // handleReset();
      // closeDrawer();
      // console.log(item)
      handleReset1(item.charger_number);
      
    }).catch((error) => {
      aShow.value = false;
    });
  }

  async function handleReset1(charger_number){
    var batteryAll = await batterylist({'charger_number':charger_number});
    batteryList.value = batteryAll;
  }

  function formSubmit() {
    formRef.value.validate((errors) => {
      if (!errors) {

        if(formParams1.value.ids.length==0){
          message.error('请选择分配的设备');
        }

        // if(formParams1.value.charger_agents_id==''||formParams1.value.charger_agents_id==null){
        //   message.error('请选择分配的代理商');
        // }

        // if(formParams1.value.charger_station_id==''||formParams1.value.charger_station_id==null){
        //   message.error('请选择分配的门店');
        // }

        // console.log("打印一下");
        // console.log(formParams1.value.ids);

        // var key = formParams1.value.ids.join(",");
        // console.log(key);

        //分配设备

        var formParams = formParams1.value;
        formParams.ids = formParams1.value.ids.join(",");



        batchCharger(formParams).then((res) => {
            showBatchModal.value = false;
            message.success('分配成功');
        });
        
        // console.log("打印一下分配的代理商id");
        // console.log(formParams1.value.charger_agents_id);

        // console.log("打印一下分配的门店id");
        // console.log(formParams1.value.charger_station_id);

        // if(formParams1.value.ids.length==0)


        // ids: null,
        // charger_agents_name: '',
        // charger_agents_id: 0,
        // charger_station_name: '',
        // charger_station_id: 0,


      } else {
        message.error('请填写完整信息');
      }
    });
  }

  function handleStation(){
    showStationModal.value = true;
  }

  function handleAgent() {
    showModalagent.value = true;
  }

  //批量分配
  function batchAllocationHandle() {
    // rowKeys.value;

    var allJson = [];

    var key = rowKeys.value;
    var keyname = rowKeysName.value;

    if(key.length==0){
      message.success("请选择批量分配的设备");
      return false;
    }
    formParams1.value.ids = key;

    showBatchModal.value = true;

    // console.log("打印一下把");
    // console.log(key[0]);
    // console.log(keyname[0]);

    // for(let i=0;i<key.length;i++){
    //   allJson.push({"id":key[i],"charger_name":keyname[i]});
    // }


    // console.log(allJson);


  }

  async function findPortHandle(record: Recordable) {
    //查看端口状态
    // console.log("查看端口");
    // console.log(record);

    //请求接口
    var batteryAll = await batterylist({'charger_number':record.charger_number});
    batteryList.value = batteryAll;

    // console.log(batteryList);
    // tableData.value = result.list;
    //弹出模态框
    showModal.value = true;
  }

  function importHandle() {
    modalShow.value = true;
  }

  function onCheckedRow(keys) {
    rowKeys.value = keys;
    rowKeysName.value = tableData.value.filter((item) => {
        return keys.includes(item.id);
      })
      .map((item) => {
        return item.charger_name;
      })
      .join(',');

    // console.log(rowKeys.value);
    // console.log(rowKeysName.value);
    // var allName = rowKeysName.value;
    // console.log(allName);
    //修改为数组
    // var nameArray = allName.split(',');

    // rowkeysChargerName.value = nameArray;
    // console.log(chars);
  }

  function reloadTable() {
    basicTableRef.value.reload();
  }

  function openCreateDrawer() {
    const { openDrawer } = createDrawerRef.value;
    openDrawer();
  }

  function handleEdit(record: Recordable) {
    drawerTitle.value = '编辑充电宝';
    const { openDrawer } = createDrawerRef.value;
    openDrawer(record.id);
  }

  function handleDelete(record: Recordable) {
    
  }

  onMounted(async () => {
    //查询一下所有的代理商
    //查询一下所有的代理商
    var agentAll1 = await getallagentList1(chargerParams.value);
    chargerParams.value.totalPage = agentAll1.totalPage;
    agentAll.value = agentAll1.list;

    //查询一下所有的门店
    // var stationAll1 = await getallStationList({});

    // stationAll.value = stationAll1;
  });
</script>

<style lang="less" scoped>

</style>
